import React, { useState, useEffect } from 'react';
import { Card, List, Button, InputNumber, Checkbox, Empty, Row, Col, Typography, message } from 'antd';
import { DeleteOutlined, ShoppingOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import { CartItem } from '../../types';
import { Storage, STORAGE_KEYS } from '../../utils/storage';
import { mockProducts } from '../../services/mockData';

const { Title, Text } = Typography;

const Cart: React.FC = () => {
  const [cartItems, setCartItems] = useState<CartItem[]>([]);
  const [selectedItems, setSelectedItems] = useState<string[]>([]);
  const navigate = useNavigate();

  useEffect(() => {
    loadCartItems();
  }, []);

  const loadCartItems = () => {
    const saved = Storage.get<CartItem[]>(STORAGE_KEYS.CART) || [];
    // 补充商品信息
    const items = saved.map(item => ({
      ...item,
      product: mockProducts.find(p => p.id === item.productId)!
    })).filter(item => item.product);
    setCartItems(items);
  };

  const saveCartItems = (items: CartItem[]) => {
    Storage.set(STORAGE_KEYS.CART, items);
    setCartItems(items);
  };

  const handleQuantityChange = (itemId: string, quantity: number) => {
    if (quantity <= 0) return;
    const newItems = cartItems.map(item =>
      item.id === itemId ? { ...item, quantity } : item
    );
    saveCartItems(newItems);
  };

  const handleRemoveItem = (itemId: string) => {
    const newItems = cartItems.filter(item => item.id !== itemId);
    saveCartItems(newItems);
    setSelectedItems(prev => prev.filter(id => id !== itemId));
    message.success('商品已从购物车移除');
  };

  const handleSelectItem = (itemId: string, checked: boolean) => {
    if (checked) {
      setSelectedItems(prev => [...prev, itemId]);
    } else {
      setSelectedItems(prev => prev.filter(id => id !== itemId));
    }
  };

  const handleSelectAll = (checked: boolean) => {
    if (checked) {
      setSelectedItems(cartItems.map(item => item.id));
    } else {
      setSelectedItems([]);
    }
  };

  const getTotalPrice = () => {
    return cartItems
      .filter(item => selectedItems.includes(item.id))
      .reduce((total, item) => total + item.product.price * item.quantity, 0);
  };

  const handleCheckout = () => {
    if (selectedItems.length === 0) {
      message.warning('请选择商品');
      return;
    }
    navigate('/order/create', { 
      state: { cartItems: cartItems.filter(item => selectedItems.includes(item.id)) }
    });
  };

  if (cartItems.length === 0) {
    return (
      <div style={{ textAlign: 'center', padding: '50px 0' }}>
        <Empty
          image={Empty.PRESENTED_IMAGE_SIMPLE}
          description="购物车是空的"
        >
          <Button type="primary" icon={<ShoppingOutlined />} onClick={() => navigate('/')}>
            去购物
          </Button>
        </Empty>
      </div>
    );
  }

  return (
    <div style={{ maxWidth: 800, margin: '0 auto' }}>
      <Title level={2}>购物车</Title>
      
      <Card>
        <div style={{ marginBottom: 16 }}>
          <Checkbox
            checked={selectedItems.length === cartItems.length}
            indeterminate={selectedItems.length > 0 && selectedItems.length < cartItems.length}
            onChange={(e) => handleSelectAll(e.target.checked)}
          >
            全选
          </Checkbox>
        </div>

        <List
          dataSource={cartItems}
          renderItem={(item) => (
            <List.Item
              actions={[
                <InputNumber
                  min={1}
                  value={item.quantity}
                  onChange={(value) => handleQuantityChange(item.id, value || 1)}
                />,
                <Button
                  type="text"
                  danger
                  icon={<DeleteOutlined />}
                  onClick={() => handleRemoveItem(item.id)}
                />
              ]}
            >
              <List.Item.Meta
                avatar={
                  <Checkbox
                    checked={selectedItems.includes(item.id)}
                    onChange={(e) => handleSelectItem(item.id, e.target.checked)}
                  />
                }
                title={
                  <Row align="middle">
                    <Col span={4}>
                      <img
                        src={item.product.image}
                        alt={item.product.name}
                        style={{ width: 60, height: 60, objectFit: 'cover', borderRadius: 4 }}
                      />
                    </Col>
                    <Col span={14}>
                      <div>{item.product.name}</div>
                      <Text type="secondary">库存: {item.product.stock}</Text>
                    </Col>
                    <Col span={6} style={{ textAlign: 'right' }}>
                      <div className="price-current">¥{item.product.price}</div>
                      <Text type="secondary">小计: ¥{(item.product.price * item.quantity).toFixed(2)}</Text>
                    </Col>
                  </Row>
                }
              />
            </List.Item>
          )}
        />

        <div style={{ 
          marginTop: 24, 
          padding: '16px 0',
          borderTop: '1px solid #f0f0f0',
          display: 'flex',
          justifyContent: 'space-between',
          alignItems: 'center'
        }}>
          <div>
            <Text>已选择 {selectedItems.length} 件商品</Text>
          </div>
          <div>
            <Text style={{ fontSize: 18, marginRight: 16 }}>
              合计: <span className="price-current">¥{getTotalPrice().toFixed(2)}</span>
            </Text>
            <Button type="primary" size="large" onClick={handleCheckout}>
              结算
            </Button>
          </div>
        </div>
      </Card>
    </div>
  );
};

export default Cart;
